<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>JavaWeb | C·辰</title><meta name="author" content="辰"><meta name="copyright" content="辰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JavaWeb# 描述">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaWeb">
<meta property="og:url" content="http://example.com/2023/04/06/JavaWeb/index.html">
<meta property="og:site_name" content="C·辰">
<meta property="og:description" content="JavaWeb# 描述">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/75b12ea49e8d7cc6cd2d0ada331f9851fe5ad27c.jpg@320w_200h_1c_!web-space-favlist-video.webp">
<meta property="article:published_time" content="2023-04-06T14:22:22.000Z">
<meta property="article:modified_time" content="2023-07-28T17:50:33.632Z">
<meta property="article:author" content="辰">
<meta property="article:tag" content="JavaWeb">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/75b12ea49e8d7cc6cd2d0ada331f9851fe5ad27c.jpg@320w_200h_1c_!web-space-favlist-video.webp"><link rel="shortcut icon" href="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Bell.ico"><link rel="canonical" href="http://example.com/2023/04/06/JavaWeb/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JavaWeb',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-29 01:50:33'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javaweb.png')"><nav id="nav"><span id="blog-info"><a href="/" title="C·辰"><span class="site-name">C·辰</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JavaWeb</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-04-06T14:22:22.000Z" title="发表于 2023-04-06 22:22:22">2023-04-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-28T17:50:33.632Z" title="更新于 2023-07-29 01:50:33">2023-07-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">7.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>32分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaWeb"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Http"><a href="#Http" class="headerlink" title="Http"></a>Http</h1><p><strong>HTTP</strong></p>
<ul>
<li>运行在TCP之上</li>
<li>端口：80</li>
</ul>
<p>Https</p>
<ul>
<li>安全的</li>
<li>443</li>
</ul>
<h2 id="Http请求"><a href="#Http请求" class="headerlink" title="Http请求"></a>Http请求</h2><h3 id="请求行"><a href="#请求行" class="headerlink" title="请求行"></a>请求行</h3><ul>
<li>请求方式：<strong>Get</strong>,<strong>Post</strong>,HEAD,DELETE,PUT,TRACT..</li>
<li><strong>get</strong>：请求能够携带的参数比较少，大小有限制，会在浏览器的URL地址栏显示数据内容，<strong>不安全</strong>，但高效</li>
<li><strong>post</strong>：请求能够携带的参数没有限制，大小有限制，会在浏览器的URL地址栏显示数据内容，<strong>安全</strong>，但高效</li>
</ul>
<h3 id="请求头"><a href="#请求头" class="headerlink" title="请求头"></a>请求头</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Accept:		     告诉浏览器，它所支持的数据类型</span><br><span class="line">Accept-Encoding:	支持哪种编码格式	GBK	UTF-<span class="number">8</span>  GB2312	Is08859-<span class="number">1</span></span><br><span class="line">Accept-Language:	告诉浏览器，它的语言环境</span><br><span class="line">Cache-Contro1:		缓存控制</span><br><span class="line">Connection:		告诉浏览器，请求完成是断开还是保持连接</span><br></pre></td></tr></table></figure>





<h2 id="Http响应"><a href="#Http响应" class="headerlink" title="Http响应"></a>Http响应</h2><h3 id="响应体"><a href="#响应体" class="headerlink" title="响应体"></a>响应体</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Accept:			告诉浏览器，它所支持的数据类型</span><br><span class="line">Accept-Encoding:	支持哪种编码格式  GBK  UTF-<span class="number">8</span>  GB2312  Is08859-<span class="number">1</span></span><br><span class="line">Accept-Language:	告诉浏览器，它的语言环境</span><br><span class="line">Cache-Control:		缓存控制</span><br><span class="line">Connection:		告诉浏览器，请求完成是断开还是保持连接</span><br><span class="line">HoST:			主机..../.</span><br><span class="line">Refresh:			告诉客户端，多久刷新一次：</span><br><span class="line">Location:			让网页重新定位；</span><br></pre></td></tr></table></figure>



<h3 id="响应状态码"><a href="#响应状态码" class="headerlink" title="响应状态码"></a>响应状态码</h3><ul>
<li>200：成功</li>
<li>3**：请求重定向（跳转指定位置）</li>
<li>4**：找不到资源  &#x2F;  资源不存在    （404）</li>
<li>5**：服务器代码错误  （500）（502：网关错误）</li>
</ul>
<h3 id="响应编码格式"><a href="#响应编码格式" class="headerlink" title="响应编码格式"></a>响应编码格式</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">resp.setContentType(<span class="string">&quot;text/html;charset=utf-8&quot;</span>);</span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="web-xml"><a href="#web-xml" class="headerlink" title="web.xml"></a>web.xml</h1><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">web-app</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">version</span>=<span class="string">&quot;4.0&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">metadata-complete</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">     </span><br><span class="line">     </span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="设置首页"><a href="#设置首页" class="headerlink" title="设置首页"></a>设置首页</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">welcome-file-list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">welcome-file</span>&gt;</span>login.jsp<span class="tag">&lt;/<span class="name">welcome-file</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">welcome-file-list</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="错误页"><a href="#错误页" class="headerlink" title="错误页"></a>错误页</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">error-page</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">error-code</span>&gt;</span>404<span class="tag">&lt;/<span class="name">error-code</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">location</span>&gt;</span>/error/404.jsp<span class="tag">&lt;/<span class="name">location</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">error-page</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">error-page</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">error-code</span>&gt;</span>500<span class="tag">&lt;/<span class="name">error-code</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">location</span>&gt;</span>/error/404.jsp<span class="tag">&lt;/<span class="name">location</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">error-page</span>&gt;</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">&lt;!--默认（404）类似转发--&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>error<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="servlet"><a href="#servlet" class="headerlink" title="servlet"></a>servlet</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--注册Servlet--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>com.chen.servlet.HelloServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--Servelt的请求路径--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="session"><a href="#session" class="headerlink" title="session"></a>session</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--设置Session默认的失效时间--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">session-config</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!--x 分钟后Session自动失效，以分钟为单位--&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">session-timeout</span>&gt;</span>15<span class="tag">&lt;/<span class="name">session-timeout</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">session-config</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a>Filter</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>com.chen.filter.CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--只要是 /servlet 的任何请求，都会经过过滤器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/servlet/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h2 id="Listener"><a href="#Listener" class="headerlink" title="Listener"></a>Listener</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--注册监听器--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>com.chen.listener.OnlineCountListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h1><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- servlet依赖 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.0.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">&lt;!-- JSP依赖 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet.jsp-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- JSTL表达式依赖 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp.jstl<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jstl-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- standard标签库--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>taglibs<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>standard<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<br>

<hr>
<br>

<br>

<h1 id="Servlet"><a href="#Servlet" class="headerlink" title="Servlet"></a>Servlet</h1><h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><ul>
<li><p>开发Servlet程序</p>
<ul>
<li>编写一个类<strong>实现Servle接口</strong></li>
<li>把开发好的Java类部署到web服务器中</li>
</ul>
</li>
<li><p><strong>把实现了Servlet接口的Java程序叫做</strong>：<strong>Servlet</strong></p>
<br></li>
</ul>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230711130130019.png" alt="image-20230711130130019"></p>
<br>



<h2 id="HelloServlet"><a href="#HelloServlet" class="headerlink" title="HelloServlet"></a>HelloServlet</h2><h3 id="1-实现Servlet接口，这里直接继承HttpServlet"><a href="#1-实现Servlet接口，这里直接继承HttpServlet" class="headerlink" title="1.实现Servlet接口，这里直接继承HttpServlet"></a>1.实现Servlet接口，这里直接继承HttpServlet</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="type">PrintWriter</span> <span class="variable">writer</span> <span class="operator">=</span> resp.getWriter();<span class="comment">//响应流</span></span><br><span class="line"></span><br><span class="line">        writer.println(<span class="string">&quot;HelloServlet&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="built_in">super</span>.doPost(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>

<h3 id="2-编写-Servlet-映射（web-xml）"><a href="#2-编写-Servlet-映射（web-xml）" class="headerlink" title="2.编写 Servlet 映射（web.xml）"></a>2.编写 <strong>Servlet 映射</strong>（web.xml）</h3><ul>
<li><strong>① 注册servlet</strong></li>
<li><strong>② 映射路径</strong></li>
</ul>
<blockquote>
<p><strong>为什么需要映射</strong>：写的是AVA程序，但是要通过刘览器访问，而浏览器需要连接Wb服务器，所以需要再web服务中注册我们写的Servlet，还需给他一个浏览器能够访问的路径；</p>
</blockquote>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--注册Servlet--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>com.chen.servlet.HelloServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--Servelt的请求路径--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h3 id="3-配置Tomcat"><a href="#3-配置Tomcat" class="headerlink" title="3.配置Tomcat"></a>3.配置Tomcat</h3><br>

<h2 id="Mapping"><a href="#Mapping" class="headerlink" title="Mapping"></a>Mapping</h2><h4 id="1-一个Servle可以指定一个映射路径"><a href="#1-一个Servle可以指定一个映射路径" class="headerlink" title="1.一个Servle可以指定一个映射路径"></a>1.一个Servle可以指定<strong>一个映射路径</strong></h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h4 id="2-一个Servlet可以指定多个映射路径"><a href="#2-一个Servlet可以指定多个映射路径" class="headerlink" title="2.一个Servlet可以指定多个映射路径"></a>2.一个Servlet可以指定<strong>多个映射路径</strong></h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hellohello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h4 id="3-一个Servleti可以指定通用映射路径"><a href="#3-一个Servleti可以指定通用映射路径" class="headerlink" title="3.一个Servleti可以指定通用映射路径"></a>3.一个Servleti可以指定<strong>通用映射路径</strong></h4><ul>
<li><strong>&#x2F;hello&#x2F;任意字符</strong></li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h4 id="4-默认请求路径"><a href="#4-默认请求路径" class="headerlink" title="4.默认请求路径"></a>4.默认请求路径</h4><ul>
<li><strong>&#x2F; 后面可以任意字符</strong></li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<h4 id="5-指定一些后缀或者前缀等等-…"><a href="#5-指定一些后缀或者前缀等等-…" class="headerlink" title="5.指定一些后缀或者前缀等等.…"></a>5.指定一些后缀或者前缀等等.…</h4><ul>
<li>.chen为后缀即可</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--可以自定义后缀实现请求映射</span></span><br><span class="line"><span class="comment">注意点，*前面不能加顶目映射的路径--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>任意字符.chen<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h4 id="6、指定错误界面"><a href="#6、指定错误界面" class="headerlink" title="6、指定错误界面"></a>6、指定错误界面</h4><ul>
<li>404</li>
<li>500</li>
<li>…</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">error-page</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">error-code</span>&gt;</span>404<span class="tag">&lt;/<span class="name">error-code</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">location</span>&gt;</span>/error/404.jsp<span class="tag">&lt;/<span class="name">location</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">error-page</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">error-page</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">error-code</span>&gt;</span>500<span class="tag">&lt;/<span class="name">error-code</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">location</span>&gt;</span>/error/404.jsp<span class="tag">&lt;/<span class="name">location</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">error-page</span>&gt;</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">&lt;!--默认（404）类似转发--&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>error<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>





<h2 id="优先级"><a href="#优先级" class="headerlink" title="优先级"></a>优先级</h2><ul>
<li><p><strong>指定了固有的映射路径优先级最高，如果找不到就会走默认的处理请求</strong></p>
</li>
<li><p><strong>小范围优先</strong></p>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--指定固有路径--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>hello<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/hello<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--默认（404）--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>error<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><br><br></p>
<h2 id="ServletContext"><a href="#ServletContext" class="headerlink" title="ServletContext"></a>ServletContext</h2><p>web容器在启动的时候，它会为每个web程序都创建一个对应的ServletContext对象，它代表了当前的web应用：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">ServletContext</span> <span class="variable">context</span> <span class="operator">=</span> <span class="built_in">this</span>.getServletContext();</span><br></pre></td></tr></table></figure>

<br>

<h3 id="1、共享数据"><a href="#1、共享数据" class="headerlink" title="1、共享数据"></a>1、共享数据</h3><ul>
<li>在这个Servlet中保存的数据，可以在另外一个servlet中拿到</li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230711160449099.png" alt="image-20230711160449099"></p>
<br>

<ul>
<li><strong>存</strong>：setAttribute(键值对)</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//将一个数据保存在了getServletContext中，键值对形式存储</span></span><br><span class="line">context.setAttribute(<span class="string">&quot;username&quot;</span>,name);</span><br></pre></td></tr></table></figure>

<br>



<ul>
<li>取：getAttribute</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">username</span> <span class="operator">=</span> (String) context.getAttribute(<span class="string">&quot;username&quot;</span>);</span><br></pre></td></tr></table></figure>



<br>

<h3 id="2、获取初始化参数"><a href="#2、获取初始化参数" class="headerlink" title="2、获取初始化参数"></a>2、获取初始化参数</h3><ul>
<li><p>可在web.xml配置初始化参数</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--配置一些web应用的初始化参数--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>url<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>jdbc:mysql://localhost:3306:参数<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>
</li>
<li><p>获取：<strong>getInitParameter(参数名称)</strong></p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> context.getInitParameter(<span class="string">&quot;url&quot;</span>);</span><br></pre></td></tr></table></figure>



<br>

<h3 id="3、请求转发"><a href="#3、请求转发" class="headerlink" title="3、请求转发"></a>3、请求转发</h3><ul>
<li><p>不是重定向，请求不跳转，只不过获取第三方资源为自己使用，当前url不变</p>
</li>
<li><p><strong>getRequestDispatcher(“转发路径”)</strong></p>
</li>
<li><p><strong>forward(req,resp)</strong></p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">RequestDispatcher</span> <span class="variable">requestDispatcher</span> <span class="operator">=</span> context.getRequestDispatcher(<span class="string">&quot;/getc&quot;</span>);<span class="comment">//转发的请求路径</span></span><br><span class="line"></span><br><span class="line">requestDispatcher.forward(req,resp);<span class="comment">//调用forward实现请求转发</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//请求转发</span></span><br><span class="line">req.getRequestDispatcher(<span class="string">&quot;success.jsp&quot;</span>).forward(req,resp);</span><br></pre></td></tr></table></figure>

<br>

<h3 id="4、读取资源文件"><a href="#4、读取资源文件" class="headerlink" title="4、读取资源文件"></a>4、读取资源文件</h3><ul>
<li><p>在java目录下新建properties</p>
</li>
<li><p>在resources目录下新建properties</p>
</li>
<li><p>发现：都被打包到了同一个路径下：classes,我们俗称这个路径为classpath:</p>
</li>
<li><p>运行后看target包下该资源文件的路径</p>
</li>
<li><p>db.properties</p>
<ul>
<li><pre><code class="properties">username=root
password=123123
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">- 读取：需要一个文件流</span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line">//target包下该资源文件的路径   </span><br><span class="line">InputStream resourceAsStream = this.getServletContext().getResourceAsStream(&quot;/WEB-INF/classes/db.properties&quot;);</span><br><span class="line">Properties properties = new Properties();</span><br><span class="line">properties.load(resourceAsStream);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">String username = properties.getProperty(&quot;username&quot;);</span><br><span class="line">String password = properties.getProperty(&quot;password&quot;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
<br>

<br>

<hr>
<br>

<br>



<h1 id="HttpServletResponse"><a href="#HttpServletResponse" class="headerlink" title="HttpServletResponse"></a>HttpServletResponse</h1><ul>
<li><p>响应数据</p>
<p>web服务器接收到客户端的http请求，针对这个请求，分别创建一个代表请求的HttpServletRequest对象，代表响应的一个HttpServletResponse;</p>
</li>
</ul>
<p>如果要获取客户端请求过来的参数：找HttpServletRequest</p>
<p>如果要给客户端响应一些信息：找HttpServletResponse</p>
<br>

<h3 id="1、分类"><a href="#1、分类" class="headerlink" title="1、分类"></a>1、分类</h3><p>负责向浏览器发送<strong>数据</strong>的方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">ServletOutputStream <span class="title function_">getOutputStream</span><span class="params">()</span> <span class="keyword">throws</span> IOException;</span><br><span class="line"></span><br><span class="line">PrintWriter <span class="title function_">getWriter</span><span class="params">()</span> <span class="keyword">throws</span> IOException;</span><br></pre></td></tr></table></figure>

<br>

<p>负责向浏览器发送<strong>响应头</strong>的方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">void</span> <span class="title function_">setCharacterEncoding</span><span class="params">(String var1)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">setContentLength</span><span class="params">(<span class="type">int</span> var1)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">setContentLengthLong</span><span class="params">(<span class="type">long</span> var1)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">setDateHeader</span><span class="params">(String var1, <span class="type">long</span> var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">addDateHeader</span><span class="params">(String var1, <span class="type">long</span> var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">setHeader</span><span class="params">(String var1, String var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">addHeader</span><span class="params">(String var1, String var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">setIntHeader</span><span class="params">(String var1, <span class="type">int</span> var2)</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">addIntHeader</span><span class="params">(String var1, <span class="type">int</span> var2)</span>;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>

<p>响应状态码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">int</span> <span class="variable">SC_OK</span> <span class="operator">=</span> <span class="number">200</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="variable">SC_FOUND</span> <span class="operator">=</span> <span class="number">302</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="variable">SC_NOT_FOUND</span> <span class="operator">=</span> <span class="number">404</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="variable">SC_INTERNAL_SERVER_ERROR</span> <span class="operator">=</span> <span class="number">500</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="variable">SC_BAD_GATEWAY</span> <span class="operator">=</span> <span class="number">502</span>;</span><br></pre></td></tr></table></figure>

<br>

<h3 id="2、向浏览器输出消息"><a href="#2、向浏览器输出消息" class="headerlink" title="2、向浏览器输出消息"></a>2、向浏览器输出消息</h3><ul>
<li><strong>getWriter</strong><ul>
<li><strong>print</strong></li>
<li><strong>write</strong></li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">test</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        resp.getWriter().println(username+<span class="string">&quot;:&quot;</span>+password);</span><br><span class="line">         resp.getWriter().write(username+<span class="string">&quot;:&quot;</span>+password);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h3 id="3、验证码功能"><a href="#3、验证码功能" class="headerlink" title="3、验证码功能"></a>3、验证码功能</h3><ul>
<li><p>前端实现</p>
</li>
<li><p>后端实现：需要用到Java的图片类，生成一个图片</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//如何让浏览器5s自动刷新一次</span></span><br><span class="line">    resp.setHeader(<span class="string">&quot;refresh&quot;</span>,<span class="string">&quot;5&quot;</span>);</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//在内存中创建一个图片</span></span><br><span class="line">    <span class="type">BufferedImage</span> <span class="variable">bufferedImage</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BufferedImage</span>(<span class="number">80</span>,<span class="number">20</span>, BufferedImage.TYPE_INT_RGB);</span><br><span class="line">    <span class="comment">//得到图片</span></span><br><span class="line">    <span class="type">Graphics2D</span> <span class="variable">graphics</span> <span class="operator">=</span> (Graphics2D)bufferedImage.getGraphics();<span class="comment">//笔</span></span><br><span class="line">    <span class="comment">//设置图片的背景颜色</span></span><br><span class="line">    graphics.setColor(Color.WHITE);</span><br><span class="line">    graphics.fillRect(<span class="number">0</span>,<span class="number">0</span>,<span class="number">80</span>,<span class="number">20</span>);</span><br><span class="line">    <span class="comment">//给图片写数据</span></span><br><span class="line">    graphics.setColor(Color.blue);</span><br><span class="line">    graphics.setFont(<span class="keyword">new</span> <span class="title class_">Font</span>(<span class="literal">null</span>,Font.BOLD,<span class="number">20</span>));</span><br><span class="line">    graphics.drawString(makeNum(),<span class="number">0</span>,<span class="number">20</span>);</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//告诉浏览器，这个请求用图片的形式打开</span></span><br><span class="line">    resp.setContentType(<span class="string">&quot;image/jpeg&quot;</span>);</span><br><span class="line">    <span class="comment">//网站存在缓存，不让浏览器缓存</span></span><br><span class="line">    resp.setDateHeader(<span class="string">&quot;expires&quot;</span>,-<span class="number">1</span>);</span><br><span class="line">    resp.setHeader(<span class="string">&quot;Cache-Control&quot;</span>,<span class="string">&quot;no-cache&quot;</span>);</span><br><span class="line">    resp.setHeader(<span class="string">&quot;Pragma&quot;</span>,<span class="string">&quot;no-cache&quot;</span>);</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//把图片写给浏览器</span></span><br><span class="line">    ImageIO.write(bufferedImage, <span class="string">&quot;jpg&quot;</span>,resp.getOutputStream());</span><br><span class="line">  </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//生成随机数</span></span><br><span class="line"><span class="keyword">private</span> String <span class="title function_">makeNum</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">Random</span> <span class="variable">random</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>();</span><br><span class="line">    <span class="type">String</span> <span class="variable">num</span> <span class="operator">=</span> random.nextInt(<span class="number">9999999</span>) + <span class="string">&quot;&quot;</span>;</span><br><span class="line">    <span class="type">StringBuffer</span> <span class="variable">stringBuffer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuffer</span>();</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">7</span>-num.length(); i++) &#123;</span><br><span class="line">        <span class="comment">//不足7为0填充</span></span><br><span class="line">        stringBuffer.append(<span class="string">&quot;0&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">String</span> <span class="variable">s</span> <span class="operator">=</span> stringBuffer.toString() + num;</span><br><span class="line">    <span class="keyword">return</span> s;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br></li>
</ul>
<h3 id="5、实现重定向"><a href="#5、实现重定向" class="headerlink" title="5、实现重定向"></a>5、实现重定向</h3><ul>
<li><strong>sendRedirect</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  resp.setHeader(&quot;Location&quot;,&quot;/responsep_war/redtext&quot;);</span></span><br><span class="line"><span class="comment">  resp.setStatus(302);</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">resp.sendRedirect(<span class="string">&quot;/responsep_war/redtext&quot;</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>面试题：请你聊聊重定向和转发的区别？<br>相同点</li>
<li>页面都会实现跳转<br>不同点<ul>
<li>请求转发的时候，url不会产生变化</li>
<li>重定向时候，url地址栏会发生变化；</li>
</ul>
</li>
</ul>
<br>

<br>

<hr>
<br>

<br>

<h1 id="HttpServletRequest"><a href="#HttpServletRequest" class="headerlink" title="HttpServletRequest"></a>HttpServletRequest</h1><p>HttpServletRequest代表客户端的请求，用户通过Http协议访问服务器，HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法，获得客户端的所有信息</p>
<h2 id="1、请求转发"><a href="#1、请求转发" class="headerlink" title="1、请求转发"></a>1、请求转发</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">req.getRequestDispatcher(<span class="string">&quot;success.jsp&quot;</span>).forward(req,resp);</span><br></pre></td></tr></table></figure>

<br>



<h2 id="2、获取前端传递数据【-】"><a href="#2、获取前端传递数据【-】" class="headerlink" title="2、获取前端传递数据【*】"></a>2、获取前端传递数据【*】</h2><ul>
<li>获取<strong>请求</strong>中的数据</li>
<li>单个：<strong>getParameter(“前端命名name”)</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">req.getParameter(<span class="string">&quot;username&quot;</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>多个：<strong>getParameterValues(“前端命名name”)</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//数组</span></span><br><span class="line">String[] hobbys = req.getParameterValues(<span class="string">&quot;hobbys&quot;</span>);</span><br><span class="line">System.out.println(Arrays.toString(hobbys));</span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="Session、Cookie"><a href="#Session、Cookie" class="headerlink" title="Session、Cookie"></a>Session、Cookie</h1><ul>
<li><strong>保存会话的两种技术</strong></li>
</ul>
<br>



<h1 id="Cookie"><a href="#Cookie" class="headerlink" title="Cookie"></a>Cookie</h1><ul>
<li>客户端技术（响应、请求）</li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230715010024931.png" alt="image-20230715010024931"></p>
<br>

<h3 id="请求获取与响应"><a href="#请求获取与响应" class="headerlink" title="请求获取与响应"></a><strong>请求获取与响应</strong></h3><p>1.从请求中拿到cookie信息</p>
<p>2.服务器响应给客户端cookie</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//从客户端获取 Cookie</span></span><br><span class="line">Cookie[] cookies = req.getCookies();<span class="comment">//返回数组，说明Cookie可能存在多个</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//遍历cookie</span></span><br><span class="line"><span class="type">Cookie</span> <span class="variable">cookie</span> <span class="operator">=</span> cookies[i];</span><br><span class="line"><span class="comment">//获取cookie的  key</span></span><br><span class="line">cookie.getName().equals(<span class="string">&quot;匹配的name&quot;</span>)</span><br><span class="line"><span class="comment">//获取cookie的  value</span></span><br><span class="line">cookie.getValue()</span><br><span class="line">     </span><br><span class="line"><span class="comment">//新建一个cookie</span></span><br><span class="line"><span class="type">Cookie</span> <span class="variable">cookie</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Cookie</span>(<span class="string">&quot;名称name&quot;</span>, 值);</span><br><span class="line"><span class="comment">//设置cookie的有效期</span></span><br><span class="line">cookie.setMaxAge(<span class="number">24</span>*<span class="number">60</span>*<span class="number">60</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//响应给客户端一个cookie</span></span><br><span class="line">resp.addCookie(cookie);</span><br></pre></td></tr></table></figure>



<ul>
<li><p>一个Cookie只能保存一个信息；</p>
</li>
<li><p>一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;</p>
</li>
<li><p>Cookie大小有限制4kb;</p>
</li>
<li><p>300个cookie浏览器上限</p>
</li>
</ul>
<br>



<h3 id="删除Cookie"><a href="#删除Cookie" class="headerlink" title="删除Cookie"></a><strong>删除Cookie</strong></h3><ul>
<li><p>不设置有效期，关闭浏览器，自动失效：</p>
</li>
<li><p>设置有效期时间为0 </p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">cookie.setMaxAge(<span class="number">0</span>);</span><br></pre></td></tr></table></figure></li>
</ul>
<br>

<h3 id="编码解码"><a href="#编码解码" class="headerlink" title="编码解码"></a><strong>编码解码</strong></h3><ul>
<li>cookie中value的<strong>值为中文</strong>的时候需要编码和解码</li>
<li>编码：URLEncoder.encode(“值”,”utf-8”));</li>
<li>解码：</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//编码</span></span><br><span class="line"><span class="type">Cookie</span> <span class="variable">cookie</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Cookie</span>(<span class="string">&quot;lastLoginTime&quot;</span>, URLEncoder.encode(<span class="string">&quot;值&quot;</span>,<span class="string">&quot;utf-8&quot;</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">//解码</span></span><br><span class="line">(URLDecoder.decode(cookie.getValue(),<span class="string">&quot;UTF-8&quot;</span>)</span><br></pre></td></tr></table></figure>



<br>

<h2 id="Cookie和Session的区别"><a href="#Cookie和Session的区别" class="headerlink" title="Cookie和Session的区别"></a>Cookie和Session的区别</h2><ul>
<li>Cookie是把用户的数据写给用户的浏览器，浏览器保存（可以保存多个）</li>
<li>Session:把用户的数据写到用户独占Session中，服务器端保存（保存重要的信息，减少服务器资源的浪费）</li>
<li>Session对象由服务创建；</li>
</ul>
<br>

<br>

<h1 id="Session【-】"><a href="#Session【-】" class="headerlink" title="Session【*】"></a>Session【*】</h1><ul>
<li>服务器技术，利用这个技术，可以保存用户的会话信息，我们可以信息或者数据放在Session中！</li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230715010204113.png" alt="image-20230715010204113"></p>
<p>使用场景：</p>
<ul>
<li><p>保存一个登录用户的信息；</p>
</li>
<li><p>购物车信息；</p>
</li>
<li><p>在整个网站中经常会使用的数据，我们将它保存在Session中；</p>
</li>
</ul>
<br>

<h3 id="获得session"><a href="#获得session" class="headerlink" title="获得session"></a>获得session</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//得到Session</span></span><br><span class="line"> <span class="type">HttpSession</span> <span class="variable">session</span> <span class="operator">=</span> req.getSession();</span><br></pre></td></tr></table></figure>

<br>

<h3 id="存入数据"><a href="#存入数据" class="headerlink" title="存入数据"></a>存入数据</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//给Session中存入东西</span></span><br><span class="line">session.setAttribute(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;辰呀&quot;</span>);</span><br></pre></td></tr></table></figure>

<br>

<h3 id="获取ID及判新"><a href="#获取ID及判新" class="headerlink" title="获取ID及判新"></a>获取ID及判新</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//获取Session的ID</span></span><br><span class="line"><span class="type">String</span> <span class="variable">sessionId</span> <span class="operator">=</span> session.getId();</span><br><span class="line"><span class="comment">//判断Session是不是新创建的</span></span><br><span class="line"><span class="keyword">if</span> (session.isNew()) &#123;</span><br><span class="line">     resp.getWriter().write(<span class="string">&quot;sessiom创建成功：ID： &quot;</span>+sessionId);</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">     resp.getWriter().write(<span class="string">&quot;session以及在服务器中存在了，ID：&quot;</span>+sessionId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h3 id="读取数据"><a href="#读取数据" class="headerlink" title="读取数据"></a>读取数据</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//获取session中的键值对应的值</span></span><br><span class="line"><span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span>(String) session.getAttribute(<span class="string">&quot;name&quot;</span>);</span><br></pre></td></tr></table></figure>

<br>

<h3 id="清除数据"><a href="#清除数据" class="headerlink" title="清除数据"></a>清除数据</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">session.removeAttribute(<span class="string">&quot;name&quot;</span>);</span><br></pre></td></tr></table></figure>

<br>

<h3 id="注销Session"><a href="#注销Session" class="headerlink" title="注销Session"></a>注销Session</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">session.invalidate();</span><br></pre></td></tr></table></figure>

<br>

<h3 id="会话自动过期"><a href="#会话自动过期" class="headerlink" title="会话自动过期"></a>会话自动过期</h3><ul>
<li>web.xml配置</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--设置Session默认的失效时间--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">session-config</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!--x 分钟后Session自动失效，以分钟为单位--&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">session-timeout</span>&gt;</span>15<span class="tag">&lt;/<span class="name">session-timeout</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">session-config</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="MVC三层架构"><a href="#MVC三层架构" class="headerlink" title="MVC三层架构"></a>MVC三层架构</h1><p><strong>MVC</strong>：Model（模型）、 view（视图） 、Controller（控制器）</p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230717005803898.png" alt="image-20230717005803898"></p>
<p><strong>Model</strong></p>
<ul>
<li>业务处理：业务逻辑（Service）</li>
<li>数据持久层：CRUD（Dao）</li>
</ul>
<br>

<p><strong>View</strong></p>
<ul>
<li>展示数据</li>
<li>提供链接发起Servlet请求(a，form，img.…)</li>
</ul>
<br>

<p><strong>Conroller（Servlet）</strong></p>
<ul>
<li>接收用户的请求：(req:请求参数、Session信息.…)</li>
<li>交给业务层处理对应的代码</li>
<li>控制视图的跳转</li>
</ul>
<figure class="highlight php"><table><tr><td class="code"><pre><span class="line">登录--&gt;接收用户的登录请求---&gt;处理用户的请求（获取用户登录的参数，username,password)----&gt;交给业务层处理登录业务（判断用户名密码是否正确：事务）---&gt;Dao层查询用户名和密码是否正确--&gt;数据库</span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>



<h1 id="过滤器【-】"><a href="#过滤器【-】" class="headerlink" title="过滤器【*】"></a>过滤器【*】</h1><p><strong>Filter</strong>:过滤器，用来过滤网站的数据；</p>
<h2 id="1、导包"><a href="#1、导包" class="headerlink" title="1、导包"></a>1、导包</h2><p>import导包需要导的是   <strong>import javax.servlet.;</strong></p>
<br>

<h2 id="2、编写过滤器"><a href="#2、编写过滤器" class="headerlink" title="2、编写过滤器"></a>2、编写过滤器</h2><ul>
<li><strong>实现</strong> Filter 接口，重写3个方法</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CharacterEncodingFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="comment">//初始化：wb服务器启动，就以及初始化了，随时等待过滤对象出现！</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;CharacterEncodingFilter已经初始化&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    	<span class="comment">/*</span></span><br><span class="line"><span class="comment">            1.过滤中的所有代码，在过滤将定清次的附族都会换行</span></span><br><span class="line"><span class="comment">            2,必须要让过滤器继续执行   filterChain.doFilter(request,response);</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">         <span class="comment">//设置处理乱码</span></span><br><span class="line">        servletRequest.setCharacterEncoding(<span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line">        servletResponse.setCharacterEncoding(<span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line">        servletResponse.setContentType(<span class="string">&quot;text/html;charset=utf-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;setCharacterEncoding执行前...&quot;</span>);</span><br><span class="line">        filterChain.doFilter(servletRequest,servletResponse);<span class="comment">//让我们的请求继续走，把请求转发下去交接，如果不写，程序在这拦截停止</span></span><br><span class="line">        System.out.println(<span class="string">&quot;setCharacterEncoding执行后...&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//销毁：服务器关闭的时候会被销毁</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;CharacterEncodingFilter已经销毁&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="3、注册Filer"><a href="#3、注册Filer" class="headerlink" title="3、注册Filer"></a>3、注册Filer</h2><ul>
<li>和注册servlet类似</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>com.chen.filter.CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--只要是 /servlet 的任何请求，都会经过过滤器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/servlet/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>



<h2 id="登录检测"><a href="#登录检测" class="headerlink" title="登录检测"></a>登录检测</h2><p>用户登录之后才能进入主页！用户注销后就不能进入主页了！</p>
<p>1、用户登录之后，向Sesison中放入用户的数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LoginServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="comment">//获取前端请求的参数</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">username</span> <span class="operator">=</span> req.getParameter(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (username.equals(<span class="string">&quot;admin&quot;</span>))&#123;</span><br><span class="line">            <span class="type">HttpSession</span> <span class="variable">session</span> <span class="operator">=</span> req.getSession();</span><br><span class="line">            session.setAttribute(<span class="string">&quot;USER_SESSION&quot;</span>,req.getSession().getId());</span><br><span class="line">            resp.sendRedirect(<span class="string">&quot;/Filer_01_war_exploded/sys/success.jsp&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            resp.sendRedirect(<span class="string">&quot;/Filer_01_war_exploded/error.jsp&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        doGet(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p>2、进入主页的时候要判断用户是否已经登录：【<strong>过滤器实现</strong>】</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SysFilter</span> <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;&#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//servletRequest    httpRequest</span></span><br><span class="line">        <span class="type">HttpServletRequest</span> <span class="variable">req</span> <span class="operator">=</span> (HttpServletRequest) servletRequest;</span><br><span class="line">        <span class="type">HttpServletResponse</span> <span class="variable">resp</span> <span class="operator">=</span> (HttpServletResponse) servletResponse;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (req.getSession().getAttribute(<span class="string">&quot;USER_SESSION&quot;</span>)==<span class="literal">null</span>)&#123;</span><br><span class="line">            resp.sendRedirect(<span class="string">&quot;/Filer_01_war_exploded/error.jsp&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        filterChain.doFilter(servletRequest,servletResponse);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<p>3、注册过滤位置</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>SysFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>com.chen.filter.SysFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>SysFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--过滤访问/sys文件夹下的文件--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/sys/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br>

<br>   

<hr>
<br>

<br>

<h1 id="监听器"><a href="#监听器" class="headerlink" title="监听器"></a>监听器</h1><h2 id="1、实现要监听对象的接口"><a href="#1、实现要监听对象的接口" class="headerlink" title="1、实现要监听对象的接口"></a>1、实现要监听对象的接口</h2><ul>
<li>实例监听session（在线人数）</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//统计网站在线人数：统计session</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OnlineCountListener</span> <span class="keyword">implements</span> <span class="title class_">HttpSessionListener</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//创建session监听：看你的一举一动</span></span><br><span class="line">    <span class="comment">//一旦创建Session.就会触发一次这个事件，</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sessionCreated</span><span class="params">(HttpSessionEvent se)</span> &#123;</span><br><span class="line">        <span class="type">ServletContext</span> <span class="variable">servletContext</span> <span class="operator">=</span> se.getSession().getServletContext();</span><br><span class="line">        System.out.println(se.getSession().getId());</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">onlineCount</span> <span class="operator">=</span> (Integer) servletContext.getAttribute(<span class="string">&quot;OnlineCount&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (onlineCount==<span class="literal">null</span>) &#123;</span><br><span class="line">            onlineCount=<span class="keyword">new</span> <span class="title class_">Integer</span>(<span class="number">2</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> onlineCount.intValue();</span><br><span class="line">            onlineCount=<span class="keyword">new</span> <span class="title class_">Integer</span>(count+<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        servletContext.setAttribute(<span class="string">&quot;onlineCount&quot;</span>,onlineCount);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//销毁session监所</span></span><br><span class="line">    <span class="comment">//一且销毁然ession就会触发一次这个事件！</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sessionDestroyed</span><span class="params">(HttpSessionEvent se)</span> &#123;</span><br><span class="line">        <span class="type">ServletContext</span> <span class="variable">servletContext</span> <span class="operator">=</span> se.getSession().getServletContext();</span><br><span class="line">        <span class="comment">//销毁</span></span><br><span class="line">        se.getSession().invalidate();</span><br><span class="line">        <span class="type">Integer</span> <span class="variable">onlineCount</span> <span class="operator">=</span> (Integer) servletContext.getAttribute(<span class="string">&quot;OnlineCount&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (onlineCount==<span class="literal">null</span>) &#123;</span><br><span class="line">            onlineCount=<span class="keyword">new</span> <span class="title class_">Integer</span>(<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> onlineCount.intValue();</span><br><span class="line">            onlineCount=<span class="keyword">new</span> <span class="title class_">Integer</span>(count-<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        servletContext.setAttribute(<span class="string">&quot;onlineCount&quot;</span>,onlineCount);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="2、注册监听器"><a href="#2、注册监听器" class="headerlink" title="2、注册监听器"></a>2、注册监听器</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--注册监听器--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>com.chen.listener.OnlineCountListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="3、JSP"><a href="#3、JSP" class="headerlink" title="3、JSP"></a>3、JSP</h2><figure class="highlight jsp"><table><tr><td class="code"><pre><span class="line">&lt;h1&gt;当前有&lt;span&gt;&lt;%=<span class="built_in">this</span>.getServletConfig().getServletContext().getAttribute(<span class="string">&quot;onlineCount&quot;</span>)%&gt;在线&lt;/span&gt;&lt;/h1&gt;</span><br></pre></td></tr></table></figure>



<h2 id="GUI中的常见用法"><a href="#GUI中的常见用法" class="headerlink" title="GUI中的常见用法"></a>GUI中的常见用法</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestPanel</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[]args)</span>&#123;</span><br><span class="line">        Frame frame=<span class="keyword">new</span> <span class="title class_">Frame</span>(<span class="string">&quot;中秋节快乐&quot;</span>);<span class="comment">//新建一个窗体</span></span><br><span class="line">        Panel panel=<span class="keyword">new</span> <span class="title class_">Panel</span>(<span class="literal">null</span>);<span class="comment">//面板</span></span><br><span class="line">        frame.setLayout(<span class="literal">null</span>);<span class="comment">//设置窗体的布局</span></span><br><span class="line">        frame.setBounds(<span class="number">300</span>,<span class="number">300</span>,<span class="number">300</span>,<span class="number">500</span>);</span><br><span class="line">        frame.setBackground(<span class="keyword">new</span> <span class="title class_">Color</span>(<span class="number">6</span>,<span class="number">0</span>,<span class="number">255</span>));<span class="comment">//设置背景颤色</span></span><br><span class="line">        panel.setBounds(<span class="number">50</span>,<span class="number">50</span>,<span class="number">300</span>,<span class="number">300</span>);</span><br><span class="line">        panel.setBackground(<span class="keyword">new</span> <span class="title class_">Color</span>(<span class="number">6</span>,<span class="number">255</span>,<span class="number">0</span>));<span class="comment">//设置背景颤色</span></span><br><span class="line">        frame.add(panel);</span><br><span class="line">        frame.setVisible(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//监听事件，监听关闭事件</span></span><br><span class="line">        frame.addWindowListener(<span class="keyword">new</span> <span class="title class_">WindowListener</span>() &#123;</span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowOpened</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;打开&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowClosing</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;关闭ing&quot;</span>);</span><br><span class="line">                System.exit(<span class="number">0</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowClosed</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;关闭ed&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowIconified</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowDeiconified</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowActivated</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;激活&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">windowDeactivated</span><span class="params">(WindowEvent e)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;未激活&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="SMBMS案例"><a href="#SMBMS案例" class="headerlink" title="SMBMS案例"></a>SMBMS案例</h1><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/clisks/article/details/101362850?ops_request_misc=%7B%22request_id%22:%22168970060916800197044463%22,%22scm%22:%2220140713.130102334..%22%7D&request_id=168970060916800197044463&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-101362850-null-null.142%5Ev89%5Echatsearch,239%5Ev2%5Einsert_chatgpt&utm_term=smbms%E8%B6%85%E5%B8%82%E8%AE%A2%E5%8D%95%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F&spm=1018.2226.3001.4187">SMBMS项目</a></p>
<br>

<br>

<hr>
<br>

<br>

<h1 id="文件传输"><a href="#文件传输" class="headerlink" title="文件传输"></a>文件传输</h1><h2 id="1、提供下载"><a href="#1、提供下载" class="headerlink" title="1、提供下载"></a>1、提供下载</h2><ul>
<li>在servlet中实现</li>
</ul>
<p>1.要获取下载文件的路径</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//1.要获取下载文件的路径</span></span><br><span class="line"><span class="type">String</span> <span class="variable">realPath</span> <span class="operator">=</span> <span class="string">&quot;D:\\1.JavaRoute\\JavaWeb\\JavaWeb\\responsep\\target\\classes\\JavaWeb.md&quot;</span>;</span><br></pre></td></tr></table></figure>

<br>

<p>2.下载的文件名是啥？</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//2( &quot;/JavaWeb.md&quot;   -----  获取最后一个&quot;/&quot;后面的字符串，所以+1)</span></span><br><span class="line"><span class="type">String</span> <span class="variable">filename</span> <span class="operator">=</span> realPath.substring(realPath.lastIndexOf(<span class="string">&quot;\\&quot;</span>) + <span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<br>

<p>3.设置想办法让浏览器能够支持下载我们需要的东西</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//3.中文文件名URLEncoder.encode编码，否则有可能乱码</span></span><br><span class="line">resp.setHeader(<span class="string">&quot;Content-disposition&quot;</span>,<span class="string">&quot;attachment;filename=&quot;</span>+ URLEncoder.encode(filename,<span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>

<p>4.获取下载文件的输入流</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">FileInputStream</span> <span class="variable">fileInputStream</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(realPath);</span><br></pre></td></tr></table></figure>

<br>

<p>5.创建缓冲区</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">int</span> len= <span class="number">0</span> ;</span><br><span class="line"><span class="type">byte</span>[] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br></pre></td></tr></table></figure>

<br>

<p>6.获取OutputStream对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">ServletOutputStream</span> <span class="variable">outputStream</span> <span class="operator">=</span> resp.getOutputStream();</span><br></pre></td></tr></table></figure>

<br>

<p>7.将FileOutputStream流写入到ouffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端！</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">while</span> (fileInputStream.read(buffer)&gt;<span class="number">0</span>)&#123;</span><br><span class="line">     outputStream.write(buffer,<span class="number">0</span>,len);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fileInputStream.close();</span><br><span class="line">outputStream.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>



<h2 id="2、文件上传"><a href="#2、文件上传" class="headerlink" title="2、文件上传"></a>2、文件上传</h2><h3 id="依赖-1"><a href="#依赖-1" class="headerlink" title="依赖"></a>依赖</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h3 id="前端"><a href="#前端" class="headerlink" title="前端"></a>前端</h3><ul>
<li>表单需要增加属性  <strong>enctype&#x3D;”multipart&#x2F;form-data”</strong></li>
</ul>
<figure class="highlight jsp"><table><tr><td class="code"><pre><span class="line">&lt;form action=<span class="string">&quot;  &quot;</span> enctype=<span class="string">&quot;multipart/form-data&quot;</span>	method=<span class="string">&quot;post&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">  &lt;input type=<span class="string">&quot;file&quot;</span> name=<span class="string">&quot;file1&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">  &lt;p&gt;&lt;input type=<span class="string">&quot;submit&quot;</span>&gt;  || &lt;input type=<span class="string">&quot;reset&quot;</span>&gt;&lt;/p&gt;</span><br><span class="line"></span><br><span class="line">&lt;/form&gt;</span><br></pre></td></tr></table></figure>

<br>

<h3 id="后端代码编写"><a href="#后端代码编写" class="headerlink" title="后端代码编写"></a>后端代码编写</h3><p><strong>ServletFileUpload类</strong></p>
<p>ServletFileUpload负责处理上传的文件数据，并将表单中每个输入项封装成一个Fileltem对象中.使用其parseRequest(HttpServletRequest)方法可以将通过表单中每一个HTML标签提交的数据封装成一个Fileltem对象，然后以List列表的形式返回。使用该方法处理上传文件简单易用。</p>
<br>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FileServlet</span> <span class="keyword">extends</span> <span class="title class_">HttpServlet</span> &#123;</span><br><span class="line">    <span class="comment">//处理表单</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">doPost</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//判断上传的文件是普通表单还是带文件的表单，两者有区别，文件的要传输，普通的表单收取字符串</span></span><br><span class="line">        <span class="keyword">if</span> (!ServletFileUpload.isMultipartContent(req)) &#123;<span class="comment">//是否包含文件</span></span><br><span class="line">            <span class="keyword">return</span>;<span class="comment">//不是，终止方法运行，说明这个一个普通的表单，直接返回</span></span><br><span class="line">        &#125;<span class="comment">//如果通过了这个if，说明我们的表单是带文件上传的</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建上传文件的保存路径，建议在WEB-INF路径下，安全，用户无法直接访问上传的文件；</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">uploadPath</span> <span class="operator">=</span> <span class="built_in">this</span>.getServletContext().getRealPath(<span class="string">&quot;WEB-INF/upload&quot;</span>);<span class="comment">//获得：全局上下文.真实地址</span></span><br><span class="line">        <span class="comment">//判断这个文件有没有</span></span><br><span class="line">        <span class="type">File</span> <span class="variable">uploadFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(uploadPath);</span><br><span class="line">        <span class="keyword">if</span> (!uploadFile.exists()) &#123;<span class="comment">//如果文件不存在</span></span><br><span class="line">            uploadFile.mkdir();<span class="comment">//创建这个目录</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">        缓存：临时文件 tmp</span></span><br><span class="line"><span class="comment">        文件上传速度太慢了，给他个中间商，慢慢上传，保证是匀速进来的</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//临时路径，假设文件超过了预期的大小，我们就把他放到一个临时文件中，过几天自动删除，或者提醒用户转存为永久</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">tmpPath</span> <span class="operator">=</span> <span class="built_in">this</span>.getServletContext().getRealPath(<span class="string">&quot;WEB-INF/tmp&quot;</span>);<span class="comment">//获得：全局上下文.真实地址</span></span><br><span class="line">        <span class="comment">//判断这个文件有没有</span></span><br><span class="line">        <span class="type">File</span> <span class="variable">file</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(tmpPath);</span><br><span class="line">        <span class="keyword">if</span> (!file.exists()) &#123;<span class="comment">//如果文件不存在</span></span><br><span class="line">            file.mkdir();<span class="comment">//创建这个临时目录</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//处理上传的文件，一般都需要通过流来获取，我们可以使用request.getInputStream(),获取原生态的文件上传流，十分麻烦</span></span><br><span class="line">        <span class="comment">//但是我们都建议使用：Apache的文件上传组件来实现，common-fileupload，他需要依赖于 commons-io组件</span></span><br><span class="line"></span><br><span class="line">   	 		<span class="comment">/*</span></span><br><span class="line"><span class="comment">            流程：</span></span><br><span class="line"><span class="comment">            ServletFileUpload负责处理上传的文件数据，并将表单中每个输入项封装成一个Fileltem对象，</span></span><br><span class="line"><span class="comment">            在使用ServletFilelpload对象（上传）解析请求时，需要DiskFileltemFactory对象。</span></span><br><span class="line"><span class="comment">            所以，我们需要在进行解析工作前构造好DiskFileltemFactory对象，</span></span><br><span class="line"><span class="comment">            通过SevletFileUpload对象的构造方法或setFileltemFactory（）方法</span></span><br><span class="line"><span class="comment">            设置ServletFileUpload对象的fileltemFactory属性。</span></span><br><span class="line"><span class="comment">    		*/</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">/*核心代码：处理这几个类*/</span></span><br><span class="line">            <span class="comment">//1.创建 DiskFileItemFactory（磁盘工厂）对象，处理文件上传路径或者大小限制</span></span><br><span class="line">            <span class="type">DiskFileItemFactory</span> <span class="variable">factory</span> <span class="operator">=</span> getDiskFileItemFactory(file);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//2.获取 ServletFileUpload</span></span><br><span class="line">            <span class="type">ServletFileUpload</span> <span class="variable">upload</span> <span class="operator">=</span> getServletFileUpload(factory);<span class="comment">//把 factory 类作为参数传递进来</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//3.处理上传的文件</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> uploadParseRequest(upload, req, uploadPath);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//servlet请求转发消息</span></span><br><span class="line">            req.setAttribute(<span class="string">&quot;msg&quot;</span>, msg);<span class="comment">//存</span></span><br><span class="line">            req.getRequestDispatcher(<span class="string">&quot;info.jsp&quot;</span>).forward(req, resp);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (FileUploadException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> DiskFileItemFactory <span class="title function_">getDiskFileItemFactory</span><span class="params">(File file)</span> &#123;</span><br><span class="line">        <span class="type">DiskFileItemFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DiskFileItemFactory</span>();</span><br><span class="line">        <span class="comment">//通过这个工厂设置一个缓存区，当上传的文件大于这个缓冲区的时候，将他放入到临时文件中</span></span><br><span class="line">        factory.setSizeThreshold(<span class="number">1024</span> * <span class="number">1024</span>);<span class="comment">//缓冲区为1M</span></span><br><span class="line">        factory.setRepository(file);<span class="comment">//临时目录的保存目录，需要一个File</span></span><br><span class="line">        <span class="keyword">return</span> factory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> ServletFileUpload <span class="title function_">getServletFileUpload</span><span class="params">(DiskFileItemFactory factory)</span> &#123;</span><br><span class="line">        <span class="type">ServletFileUpload</span> <span class="variable">upload</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ServletFileUpload</span>(factory);</span><br><span class="line">        <span class="comment">//监听文件的上传进度</span></span><br><span class="line">        upload.setProgressListener(<span class="keyword">new</span> <span class="title class_">ProgressListener</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="comment">//pBytesRead：已经读取到的文件大小</span></span><br><span class="line">            <span class="comment">//pContentLength：文件大小</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(<span class="type">long</span> pBytesRead, <span class="type">long</span> pContentLength, <span class="type">int</span> pItems)</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;总大小：&quot;</span> + pContentLength + <span class="string">&quot;已上传：&quot;</span> + pBytesRead);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">//处理乱码问题</span></span><br><span class="line">        upload.setHeaderEncoding(<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">//设置单个文件的最大值</span></span><br><span class="line">        upload.setFileSizeMax(<span class="number">1024</span> * <span class="number">1024</span> * <span class="number">10</span>);</span><br><span class="line">        <span class="comment">//设置总共能够上传文件的大小</span></span><br><span class="line">        <span class="comment">//1024 = 1kb * 1024 = 1M * 10 = 10M</span></span><br><span class="line">        upload.setSizeMax(<span class="number">1024</span> * <span class="number">1024</span> * <span class="number">10</span>);</span><br><span class="line">        <span class="keyword">return</span> upload;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">uploadParseRequest</span><span class="params">(ServletFileUpload upload, HttpServletRequest request, String uploadPath)</span> <span class="keyword">throws</span> IOException, FileUploadException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">msg</span> <span class="operator">=</span> <span class="string">&quot;&quot;</span>;</span><br><span class="line">        <span class="comment">//3.把前端请求解析，封装成一个FileItem对象，需要从ServletFileUpload对象中获取</span></span><br><span class="line">        List&lt;FileItem&gt; fileItems = upload.parseRequest(request);</span><br><span class="line">        <span class="comment">//fileItem 每一个表单对象</span></span><br><span class="line">        <span class="keyword">for</span> (FileItem fileItem : fileItems) &#123;</span><br><span class="line">            <span class="comment">//判断上传的文件（控件）是普通的表单还是带文件的表单，判断是不是 input file</span></span><br><span class="line">            <span class="keyword">if</span> (fileItem.isFormField()) &#123;<span class="comment">//普通表单</span></span><br><span class="line">                <span class="comment">//getFieldName:前端表单控件的name</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> fileItem.getFieldName();</span><br><span class="line">                <span class="type">String</span> <span class="variable">value</span> <span class="operator">=</span> fileItem.getString(<span class="string">&quot;UTF-8&quot;</span>);<span class="comment">//处理乱码</span></span><br><span class="line">                System.out.println(name + <span class="string">&quot;:&quot;</span> + value);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123; <span class="comment">//文件表单 ，（用到工具类）</span></span><br><span class="line">                <span class="comment">//===============处理文件===================</span></span><br><span class="line">                <span class="comment">//拿到文件名字</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">uploadFileName</span> <span class="operator">=</span> fileItem.getName();</span><br><span class="line">                System.out.println(<span class="string">&quot;上传的文件名：&quot;</span> + uploadFileName);</span><br><span class="line">                <span class="comment">//判断文件名</span></span><br><span class="line">                <span class="keyword">if</span> (uploadFileName.trim().equals(<span class="string">&quot;&quot;</span>) || uploadFileName == <span class="literal">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">//获得上传的文件名  /images/girl/paojie/png</span></span><br><span class="line">                <span class="comment">//字符串游戏</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">fileName</span> <span class="operator">=</span> uploadFileName.substring(uploadFileName.lastIndexOf(<span class="string">&quot;/&quot;</span>) + <span class="number">1</span>);<span class="comment">//最后一个 / +1</span></span><br><span class="line">                <span class="comment">//获得文件的后缀名</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">fileExtName</span> <span class="operator">=</span> uploadFileName.substring(uploadFileName.lastIndexOf(<span class="string">&quot;.&quot;</span>) + <span class="number">1</span>);</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">                        如果文件后缀名 fileExtName 不是我们需要的，</span></span><br><span class="line"><span class="comment">                        就直接return，不处理，告诉用户文件类型不对。</span></span><br><span class="line"><span class="comment">                     */</span></span><br><span class="line">                System.out.println(<span class="string">&quot;文件信息[件名：&quot;</span> + fileName + <span class="string">&quot;---文件类型&quot;</span> + fileExtName + <span class="string">&quot;]&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*面试题</span></span><br><span class="line"><span class="comment">          网络传输中的东西，都需要序列化</span></span><br><span class="line"><span class="comment">          POJO，实体类，如果想要在多个电脑上运行，  需要：传输==&gt;把对象都序列化了</span></span><br><span class="line"><span class="comment">          写POJO实体类时，把这个接口 implements Serializable 加上 ，标记接口（没有方法的接口）</span></span><br><span class="line"><span class="comment">          标记接口：java虚拟机（JVM）在运行到的时候，它去识别，假设实现了 Serializable 这个接口，会帮你做一些事情。</span></span><br><span class="line"><span class="comment">          JVM中有一个本地方法栈：native，它是调用C++的，java虚拟机底层是C++写的。</span></span><br><span class="line"><span class="comment">          JNI = Java Native Interface  java本地化接口，</span></span><br><span class="line"><span class="comment">          java是无法操作计算机的，java是操作JVM的，JVM操作计算机（操作系统）</span></span><br><span class="line"><span class="comment">          JVM中还有一个java栈，平时写东西在java栈中写，本地方法栈是C++做的、操作系统来做</span></span><br><span class="line"><span class="comment">          公司里常用UUID，这个安全</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">//可以使用UUID（唯一识别的通用码），保证文件名唯一</span></span><br><span class="line">                <span class="comment">//UUID.randomUUID():随机生成一个唯一识别的通用码</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">uuidPath</span> <span class="operator">=</span> UUID.randomUUID().toString();</span><br><span class="line"></span><br><span class="line">                <span class="comment">//===============处理文件完毕===================</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">//文件存到哪？ uploadPath</span></span><br><span class="line">                <span class="comment">//文件真实存在的路径 realPath</span></span><br><span class="line">                <span class="type">String</span> <span class="variable">realPath</span> <span class="operator">=</span> uploadPath + <span class="string">&quot;/&quot;</span> + uuidPath;</span><br><span class="line">                <span class="comment">//给每个文件创建一个对应的文件夹</span></span><br><span class="line">                <span class="type">File</span> <span class="variable">realPathFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(realPath);</span><br><span class="line">                <span class="keyword">if</span> (!realPathFile.exists()) &#123;<span class="comment">//不存在</span></span><br><span class="line">                    realPathFile.mkdir();<span class="comment">//创建文件夹，保证不会重复</span></span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">                <span class="comment">//===============存放地址完毕===================</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">//获得文件上传的流</span></span><br><span class="line">                <span class="type">InputStream</span> <span class="variable">inputStream</span> <span class="operator">=</span> fileItem.getInputStream();</span><br><span class="line"></span><br><span class="line">                <span class="comment">//创建一个文件输出流</span></span><br><span class="line">                <span class="type">FileOutputStream</span> <span class="variable">fos</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(realPath + <span class="string">&quot;/&quot;</span> + fileName);<span class="comment">// 输出的地址</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">//创建一个缓存区</span></span><br><span class="line">                <span class="type">byte</span>[] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line"></span><br><span class="line">                <span class="comment">//判断是否读取完毕</span></span><br><span class="line">                <span class="type">int</span> <span class="variable">len</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">                <span class="comment">//如果大于0说明还存在数据</span></span><br><span class="line">                <span class="keyword">while</span> ((len = inputStream.read(buffer)) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    fos.write(buffer, <span class="number">0</span>, len);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">//关闭流</span></span><br><span class="line">                fos.close();</span><br><span class="line">                inputStream.close();</span><br><span class="line"></span><br><span class="line">                msg = <span class="string">&quot;文件上传成功&quot;</span>;</span><br><span class="line">                fileItem.delete();<span class="comment">//上传成功，清除临时文件</span></span><br><span class="line">                <span class="comment">//===============文件传输完毕===================</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> msg;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="邮件发送"><a href="#邮件发送" class="headerlink" title="邮件发送"></a>邮件发送</h1><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230721180927506.png" alt="image-20230721180927506"></p>
<br>

<h2 id="依赖-2"><a href="#依赖-2" class="headerlink" title="依赖"></a>依赖</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.activation<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>activation<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.mail<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mail<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.4.7<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br>

<h2 id="1、简单文本邮件"><a href="#1、简单文本邮件" class="headerlink" title="1、简单文本邮件"></a>1、简单文本邮件</h2><ul>
<li><p>邮件验证码(开线程实现)</p>
</li>
<li><blockquote>
<p>&#x2F;&#x2F;用户注册成功之后，给用户发送一封娜件<br>&#x2F;&#x2F;我们使用线程米专门发送娜件，防止出现耗时，和网站注册人数过多的情况：<br>Sendmail send new Sendmail(user);<br>&#x2F;&#x2F;启动线程，线程启动之后就会执行run方法来发送娜件<br>send.start();</p>
</blockquote>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MailTest01</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> MessagingException, GeneralSecurityException &#123;</span><br><span class="line">        <span class="type">Properties</span> <span class="variable">prop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mai1.host&quot;</span>,<span class="string">&quot;smtp.qq.com&quot;</span>);<span class="comment">//设置e邮件服务器</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.transport.protocol&quot;</span>,<span class="string">&quot;smtp&quot;</span>);<span class="comment">//邮件发送协议</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp,auth&quot;</span>,<span class="string">&quot;true&quot;</span>);<span class="comment">//需要验证用户名密码</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关于QQ邮箱，还要设置ssL加密，加上以下代码即可</span></span><br><span class="line">        <span class="type">MailSSLSocketFactory</span> <span class="variable">sf</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MailSSLSocketFactory</span>();</span><br><span class="line">        sf.setTrustAllHosts(<span class="literal">true</span>);</span><br><span class="line">        prop.put(<span class="string">&quot;mail.smtp.ssl.enable&quot;</span>,<span class="string">&quot;true&quot;</span>);</span><br><span class="line">        prop.put(<span class="string">&quot;mail.smtp.ssl.socketFactory&quot;</span>,sf);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用avaMaiL发送娜件的5个步骤</span></span><br><span class="line">        <span class="comment">//1、创建定义整个应用程序所需的环境信息的Session对象</span></span><br><span class="line">        <span class="comment">//QQ才有！其他邮箱就不用</span></span><br><span class="line">        <span class="type">Session</span> <span class="variable">session</span> <span class="operator">=</span> Session.getDefaultInstance(prop,<span class="keyword">new</span> <span class="title class_">Authenticator</span>()&#123;</span><br><span class="line">            <span class="keyword">public</span> PasswordAuthentication <span class="title function_">getpasswordAuthentication</span><span class="params">()</span> &#123;</span><br><span class="line">                <span class="comment">//发件人邮件用户名、授权码</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">PasswordAuthentication</span>(<span class="string">&quot;1107383160@qq.com&quot;</span>, <span class="string">&quot;授权码&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2、通过session得到transport.对象</span></span><br><span class="line">        <span class="type">Transport</span> <span class="variable">ts</span> <span class="operator">=</span> session.getTransport();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3、使用邮箱的用户名和授权码连上邮件服务器</span></span><br><span class="line">        ts.connect(<span class="string">&quot;smtp.qq.com&quot;</span>,<span class="string">&quot;1107383160@qq.com&quot;</span>,<span class="string">&quot;授权码&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4、创建邮件</span></span><br><span class="line">        <span class="comment">//传递sesson</span></span><br><span class="line">        <span class="type">MimeMessage</span> <span class="variable">message</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MimeMessage</span>(session);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//指明邮件的发件人</span></span><br><span class="line">        message.setFrom(<span class="keyword">new</span> <span class="title class_">InternetAddress</span>(<span class="string">&quot;1107383160@qq.com&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发</span></span><br><span class="line">        message.setRecipient(Message.RecipientType.TO,<span class="keyword">new</span> <span class="title class_">InternetAddress</span>(<span class="string">&quot;2931303919@qq.com&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//邮件的标题</span></span><br><span class="line">        message.setSubject(<span class="string">&quot;黄芪，text&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//==============================================================================================</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//简单文本邮件</span></span><br><span class="line">        message.setContent(<span class="string">&quot;你好啊！&quot;</span>,<span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//==============================================================================================</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//5、发送邮件</span></span><br><span class="line">        ts.sendMessage(message,message.getAllRecipients());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6、关闭连接</span></span><br><span class="line">        ts.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<br>

<h2 id="2、带图片邮件"><a href="#2、带图片邮件" class="headerlink" title="2、带图片邮件"></a>2、带图片邮件</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//==============================================================================================</span></span><br><span class="line"><span class="comment">//图片附件邮件</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//准备图片数据</span></span><br><span class="line"><span class="type">MimeBodyPart</span> <span class="variable">image</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MimeBodyPart</span>();</span><br><span class="line"><span class="comment">//图片需要经过数据处理.·DataHandLer:数据处理</span></span><br><span class="line"><span class="type">DataHandler</span> <span class="variable">dh</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DataHandler</span>(<span class="keyword">new</span> <span class="title class_">FileDataSource</span>(<span class="string">&quot;D:\\1.JavaRoute\\JavaWeb\\JavaWeb\\Email\\web\\img\\ikun.png&quot;</span>));</span><br><span class="line">image.setDataHandler(dh);<span class="comment">//我们的Body中放入这个处理的图片数据</span></span><br><span class="line">image.setContentID(<span class="string">&quot;bz.jpg&quot;</span>);<span class="comment">//给图片设置一个D,我们在后面可以使用！(cid)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//准备正文数据</span></span><br><span class="line"><span class="type">MimeBodyPart</span> <span class="variable">text</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MimeBodyPart</span>();</span><br><span class="line">text.setContent(<span class="string">&quot;这是一封邮件正文带图片的邮件&lt;img src=&#x27;cid:bz.jpg&#x27;&gt;&quot;</span>,<span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//描述数据关系</span></span><br><span class="line"><span class="type">MimeMultipart</span> <span class="variable">mm</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MimeMultipart</span>();</span><br><span class="line">mm.addBodyPart(text);</span><br><span class="line">mm.addBodyPart(image);</span><br><span class="line">mm.setSubType(<span class="string">&quot;related&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//设置到消息中，保存修改</span></span><br><span class="line">message.setContent(mm);<span class="comment">//把最后编辑好的邮件放到消息当中</span></span><br><span class="line">message.saveChanges();<span class="comment">//保存修政！</span></span><br><span class="line"><span class="comment">//==============================================================================================</span></span><br></pre></td></tr></table></figure>





</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">辰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/04/06/JavaWeb/">http://example.com/2023/04/06/JavaWeb/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">C·辰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaWeb/">JavaWeb</a></div><div class="post_share"><div class="social-share" data-image="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/75b12ea49e8d7cc6cd2d0ada331f9851fe5ad27c.jpg@320w_200h_1c_!web-space-favlist-video.webp" data-sites="wechat,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/04/06/%E6%9C%8D%E5%8A%A1%E5%99%A8/" title="阿里服务器&amp;图床"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/ali.gif" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">阿里服务器&amp;图床</div></div></a></div><div class="next-post pull-right"><a href="/2023/04/06/Java%E5%8F%8D%E5%B0%84/" title="Java反射"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/annotayion.webp" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java反射</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">辰</div><div class="author-info__description">车遥马慢</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/hchenp"><i class="fab fa-github"></i><span>Gitee-HchenP</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/hchenp" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://github.com/Pxlchen?tab=projects" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="https://console.cloud.tencent.com/cos/bucket?bucket=chen-1317386995&amp;region=ap-guangzhou&amp;isPublic=true" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="mailto:1107383160@qq.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">C2C-Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Http"><span class="toc-number">1.</span> <span class="toc-text">Http</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Http%E8%AF%B7%E6%B1%82"><span class="toc-number">1.1.</span> <span class="toc-text">Http请求</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E8%A1%8C"><span class="toc-number">1.1.1.</span> <span class="toc-text">请求行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%A4%B4"><span class="toc-number">1.1.2.</span> <span class="toc-text">请求头</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Http%E5%93%8D%E5%BA%94"><span class="toc-number">1.2.</span> <span class="toc-text">Http响应</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E4%BD%93"><span class="toc-number">1.2.1.</span> <span class="toc-text">响应体</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E7%8A%B6%E6%80%81%E7%A0%81"><span class="toc-number">1.2.2.</span> <span class="toc-text">响应状态码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E7%BC%96%E7%A0%81%E6%A0%BC%E5%BC%8F"><span class="toc-number">1.2.3.</span> <span class="toc-text">响应编码格式</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#web-xml"><span class="toc-number">2.</span> <span class="toc-text">web.xml</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E9%A6%96%E9%A1%B5"><span class="toc-number">2.1.</span> <span class="toc-text">设置首页</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%94%99%E8%AF%AF%E9%A1%B5"><span class="toc-number">2.2.</span> <span class="toc-text">错误页</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#servlet"><span class="toc-number">2.3.</span> <span class="toc-text">servlet</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#session"><span class="toc-number">2.4.</span> <span class="toc-text">session</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Filter"><span class="toc-number">2.5.</span> <span class="toc-text">Filter</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Listener"><span class="toc-number">2.6.</span> <span class="toc-text">Listener</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96"><span class="toc-number">3.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Servlet"><span class="toc-number">4.</span> <span class="toc-text">Servlet</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-number">4.1.</span> <span class="toc-text">简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E7%90%86"><span class="toc-number">4.2.</span> <span class="toc-text">原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#HelloServlet"><span class="toc-number">4.3.</span> <span class="toc-text">HelloServlet</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%9E%E7%8E%B0Servlet%E6%8E%A5%E5%8F%A3%EF%BC%8C%E8%BF%99%E9%87%8C%E7%9B%B4%E6%8E%A5%E7%BB%A7%E6%89%BFHttpServlet"><span class="toc-number">4.3.1.</span> <span class="toc-text">1.实现Servlet接口，这里直接继承HttpServlet</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E7%BC%96%E5%86%99-Servlet-%E6%98%A0%E5%B0%84%EF%BC%88web-xml%EF%BC%89"><span class="toc-number">4.3.2.</span> <span class="toc-text">2.编写 Servlet 映射（web.xml）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%85%8D%E7%BD%AETomcat"><span class="toc-number">4.3.3.</span> <span class="toc-text">3.配置Tomcat</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Mapping"><span class="toc-number">4.4.</span> <span class="toc-text">Mapping</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E4%B8%80%E4%B8%AAServle%E5%8F%AF%E4%BB%A5%E6%8C%87%E5%AE%9A%E4%B8%80%E4%B8%AA%E6%98%A0%E5%B0%84%E8%B7%AF%E5%BE%84"><span class="toc-number">4.4.0.1.</span> <span class="toc-text">1.一个Servle可以指定一个映射路径</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E4%B8%80%E4%B8%AAServlet%E5%8F%AF%E4%BB%A5%E6%8C%87%E5%AE%9A%E5%A4%9A%E4%B8%AA%E6%98%A0%E5%B0%84%E8%B7%AF%E5%BE%84"><span class="toc-number">4.4.0.2.</span> <span class="toc-text">2.一个Servlet可以指定多个映射路径</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E4%B8%80%E4%B8%AAServleti%E5%8F%AF%E4%BB%A5%E6%8C%87%E5%AE%9A%E9%80%9A%E7%94%A8%E6%98%A0%E5%B0%84%E8%B7%AF%E5%BE%84"><span class="toc-number">4.4.0.3.</span> <span class="toc-text">3.一个Servleti可以指定通用映射路径</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-%E9%BB%98%E8%AE%A4%E8%AF%B7%E6%B1%82%E8%B7%AF%E5%BE%84"><span class="toc-number">4.4.0.4.</span> <span class="toc-text">4.默认请求路径</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5-%E6%8C%87%E5%AE%9A%E4%B8%80%E4%BA%9B%E5%90%8E%E7%BC%80%E6%88%96%E8%80%85%E5%89%8D%E7%BC%80%E7%AD%89%E7%AD%89-%E2%80%A6"><span class="toc-number">4.4.0.5.</span> <span class="toc-text">5.指定一些后缀或者前缀等等.…</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%E3%80%81%E6%8C%87%E5%AE%9A%E9%94%99%E8%AF%AF%E7%95%8C%E9%9D%A2"><span class="toc-number">4.4.0.6.</span> <span class="toc-text">6、指定错误界面</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BC%98%E5%85%88%E7%BA%A7"><span class="toc-number">4.5.</span> <span class="toc-text">优先级</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ServletContext"><span class="toc-number">4.6.</span> <span class="toc-text">ServletContext</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%85%B1%E4%BA%AB%E6%95%B0%E6%8D%AE"><span class="toc-number">4.6.1.</span> <span class="toc-text">1、共享数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E8%8E%B7%E5%8F%96%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%82%E6%95%B0"><span class="toc-number">4.6.2.</span> <span class="toc-text">2、获取初始化参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91"><span class="toc-number">4.6.3.</span> <span class="toc-text">3、请求转发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81%E8%AF%BB%E5%8F%96%E8%B5%84%E6%BA%90%E6%96%87%E4%BB%B6"><span class="toc-number">4.6.4.</span> <span class="toc-text">4、读取资源文件</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HttpServletResponse"><span class="toc-number">5.</span> <span class="toc-text">HttpServletResponse</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%86%E7%B1%BB"><span class="toc-number">5.0.1.</span> <span class="toc-text">1、分类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%90%91%E6%B5%8F%E8%A7%88%E5%99%A8%E8%BE%93%E5%87%BA%E6%B6%88%E6%81%AF"><span class="toc-number">5.0.2.</span> <span class="toc-text">2、向浏览器输出消息</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E9%AA%8C%E8%AF%81%E7%A0%81%E5%8A%9F%E8%83%BD"><span class="toc-number">5.0.3.</span> <span class="toc-text">3、验证码功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E5%AE%9E%E7%8E%B0%E9%87%8D%E5%AE%9A%E5%90%91"><span class="toc-number">5.0.4.</span> <span class="toc-text">5、实现重定向</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HttpServletRequest"><span class="toc-number">6.</span> <span class="toc-text">HttpServletRequest</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91"><span class="toc-number">6.1.</span> <span class="toc-text">1、请求转发</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E8%8E%B7%E5%8F%96%E5%89%8D%E7%AB%AF%E4%BC%A0%E9%80%92%E6%95%B0%E6%8D%AE%E3%80%90-%E3%80%91"><span class="toc-number">6.2.</span> <span class="toc-text">2、获取前端传递数据【*】</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Session%E3%80%81Cookie"><span class="toc-number">7.</span> <span class="toc-text">Session、Cookie</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Cookie"><span class="toc-number">8.</span> <span class="toc-text">Cookie</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E8%8E%B7%E5%8F%96%E4%B8%8E%E5%93%8D%E5%BA%94"><span class="toc-number">8.0.1.</span> <span class="toc-text">请求获取与响应</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%A0%E9%99%A4Cookie"><span class="toc-number">8.0.2.</span> <span class="toc-text">删除Cookie</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%96%E7%A0%81%E8%A7%A3%E7%A0%81"><span class="toc-number">8.0.3.</span> <span class="toc-text">编码解码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Cookie%E5%92%8CSession%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">8.1.</span> <span class="toc-text">Cookie和Session的区别</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Session%E3%80%90-%E3%80%91"><span class="toc-number">9.</span> <span class="toc-text">Session【*】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%BE%97session"><span class="toc-number">9.0.1.</span> <span class="toc-text">获得session</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%98%E5%85%A5%E6%95%B0%E6%8D%AE"><span class="toc-number">9.0.2.</span> <span class="toc-text">存入数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96ID%E5%8F%8A%E5%88%A4%E6%96%B0"><span class="toc-number">9.0.3.</span> <span class="toc-text">获取ID及判新</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%BB%E5%8F%96%E6%95%B0%E6%8D%AE"><span class="toc-number">9.0.4.</span> <span class="toc-text">读取数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B8%85%E9%99%A4%E6%95%B0%E6%8D%AE"><span class="toc-number">9.0.5.</span> <span class="toc-text">清除数据</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E9%94%80Session"><span class="toc-number">9.0.6.</span> <span class="toc-text">注销Session</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%9A%E8%AF%9D%E8%87%AA%E5%8A%A8%E8%BF%87%E6%9C%9F"><span class="toc-number">9.0.7.</span> <span class="toc-text">会话自动过期</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#MVC%E4%B8%89%E5%B1%82%E6%9E%B6%E6%9E%84"><span class="toc-number">10.</span> <span class="toc-text">MVC三层架构</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%BF%87%E6%BB%A4%E5%99%A8%E3%80%90-%E3%80%91"><span class="toc-number">11.</span> <span class="toc-text">过滤器【*】</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%AF%BC%E5%8C%85"><span class="toc-number">11.1.</span> <span class="toc-text">1、导包</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E7%BC%96%E5%86%99%E8%BF%87%E6%BB%A4%E5%99%A8"><span class="toc-number">11.2.</span> <span class="toc-text">2、编写过滤器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E6%B3%A8%E5%86%8CFiler"><span class="toc-number">11.3.</span> <span class="toc-text">3、注册Filer</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%99%BB%E5%BD%95%E6%A3%80%E6%B5%8B"><span class="toc-number">11.4.</span> <span class="toc-text">登录检测</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">12.</span> <span class="toc-text">监听器</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%AE%9E%E7%8E%B0%E8%A6%81%E7%9B%91%E5%90%AC%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%8E%A5%E5%8F%A3"><span class="toc-number">12.1.</span> <span class="toc-text">1、实现要监听对象的接口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E6%B3%A8%E5%86%8C%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">12.2.</span> <span class="toc-text">2、注册监听器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81JSP"><span class="toc-number">12.3.</span> <span class="toc-text">3、JSP</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#GUI%E4%B8%AD%E7%9A%84%E5%B8%B8%E8%A7%81%E7%94%A8%E6%B3%95"><span class="toc-number">12.4.</span> <span class="toc-text">GUI中的常见用法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#SMBMS%E6%A1%88%E4%BE%8B"><span class="toc-number">13.</span> <span class="toc-text">SMBMS案例</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%BC%A0%E8%BE%93"><span class="toc-number">14.</span> <span class="toc-text">文件传输</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E6%8F%90%E4%BE%9B%E4%B8%8B%E8%BD%BD"><span class="toc-number">14.1.</span> <span class="toc-text">1、提供下载</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="toc-number">14.2.</span> <span class="toc-text">2、文件上传</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96-1"><span class="toc-number">14.2.1.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E7%AB%AF"><span class="toc-number">14.2.2.</span> <span class="toc-text">前端</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%8E%E7%AB%AF%E4%BB%A3%E7%A0%81%E7%BC%96%E5%86%99"><span class="toc-number">14.2.3.</span> <span class="toc-text">后端代码编写</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%82%AE%E4%BB%B6%E5%8F%91%E9%80%81"><span class="toc-number">15.</span> <span class="toc-text">邮件发送</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96-2"><span class="toc-number">15.1.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E7%AE%80%E5%8D%95%E6%96%87%E6%9C%AC%E9%82%AE%E4%BB%B6"><span class="toc-number">15.2.</span> <span class="toc-text">1、简单文本邮件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%B8%A6%E5%9B%BE%E7%89%87%E9%82%AE%E4%BB%B6"><span class="toc-number">15.3.</span> <span class="toc-text">2、带图片邮件</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javaall.gif" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java八股文"/></a><div class="content"><a class="title" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文">Java八股文</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javahd.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java后端"/></a><div class="content"><a class="title" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端">Java后端</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/06/02/MybatisPlus/" title="MybatisPlus"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MybatisPlus"/></a><div class="content"><a class="title" href="/2023/06/02/MybatisPlus/" title="MybatisPlus">MybatisPlus</a><time datetime="2023-06-02T14:22:22.000Z" title="发表于 2023-06-02 22:22:22">2023-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Linux/" title="Linux"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Linux.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Linux"/></a><div class="content"><a class="title" href="/2023/05/05/Linux/" title="Linux">Linux</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Redis/" title="Redis"><img src= "" data-lazy-src="/img/loading.gif" data-original="ttps://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Redis.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis"/></a><div class="content"><a class="title" href="/2023/05/05/Redis/" title="Redis">Redis</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 辰</div><div class="framework-info"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn">粤ICP备2023096650号</a><span class="footer-separator">|</span><a target="_blank" rel="noopener" href="http://hchen.cloud">hchen.cloud</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>